package com.qf.openapi.web.master.controller;

import com.qf.openapi.web.master.utils.Constants;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@Controller
public class DownloadController {

    @GetMapping("/download")
    public void downloag(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {

        //1. 根据文件名找到文件 ，把文件内容写回response对象的输出流中
        final String realPath = request.getServletContext().getRealPath(Constants.UPLOAD_PATH);

        final String finalfilePath = realPath + File.separator + filename;

        //2. 添加文件下载的响应头
        //设置响应头  告知浏览器，要以附件的形式保存内容   filename=浏览器显示的下载文件名
        response.setHeader("content-disposition","attachment;filename="+filename);

        IOUtils.copy(new FileInputStream(finalfilePath),response.getOutputStream());

    }
}
